package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        // 1、查询blog
        Blog blog = getById(id);
        // 2、blog存在则查询用户并返回
        if(blog == null){
            return Result.fail("博客不存在！");
        }
        queryBlogUser(blog);
        // 3、判断是被点过赞
        isLikeBlog(blog);
        return Result.ok(blog);
    }

    private void isLikeBlog(Blog blog) {
        // 1、获取用户信息
        UserDTO userDTO = UserHolder.getUser();
        if(userDTO == null){
            return ;
        }
        Long userId = UserHolder.getUser().getId();
        // 2、判断redis中对应文章是否存在该用户号
        Long id = blog.getId();
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        // 3、给Blog的isLike赋值，用于前端展示
        blog.setIsLike(score != null);
    }

    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            isLikeBlog(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {
        // 1、获取用户id
        Long userId = UserHolder.getUser().getId();
        // 2、从redis中判断该用户是否对此点过赞
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        // 3.1、未点过赞，修改数据库点赞数量
        if(score == null){
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            // 3.2、修改redis中的数据 zadd key value score
            if(isSuccess){
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }else {
            // 4.1 点过赞，取消点赞，数据库-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            // 4.2 redis中删除点赞用户
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 1、查询top5的点赞用户（点赞时间排序）zrange key 0 4
        String key = BLOG_LIKED_KEY + id;
        Set<String> set = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(set == null || set.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        // 2、将set转为UserDTO的List
        // 需要自定义查询，因为mybatis plus查询出的不是按照时间顺序,因此需要通过order by field(id, 指定顺序) - 指定顺序（即查询出的顺序）
        List<Long> ids = set.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + join + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long id) {
        Page<Blog> page = query().eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页面
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1、获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2、保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增用户笔记失败");
        }
        // 3、获取粉丝id - select from tb_follow where follow_user_id = ?
        List<Follow> Fans = followService.query().eq("follow_user_id", user.getId()).list();
        // 4、给每个粉丝推送（收件箱即SortedSet）
        for(Follow follow : Fans){
            // 4.1、获取粉丝redis中的收件箱
            String key = FEED_KEY + follow.getUserId();
            // 4.2、向粉丝收件箱中发送blog并记录时间
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 5、返回id
        return Result.ok(blog.getId());
    }

    // 分页查询该用户最新的订阅推送博客，但可能其关注的博主同时发布博客，因此需要记录每次查询的偏移值进行不重复的查看博客
    @Override
    public Result queryBlogOfFollow(Long max, Long offset) {
        // 1、获取当前用户id
        Long userId = UserHolder.getUser().getId();
        // 2、获取获取用户收件箱(获取收件箱，即新发布的推给你的内容，旧的获取不到）
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 3、分页获取长度的blog列表，遍历ZSet中获取的列表，遍历获取blog列表和最大值和本次出现最大值的偏移量
        long minTime = 0;
        int os = 0;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            // 遍历得到最小分数
            os = 1;
            long time = tuple.getScore().longValue();
            // 遍历获取最小值的偏移量
            if(time == minTime){
                os++;
            }else {
                minTime = time;
                os = 1;
            }
        }
        // 4、将blog的id转为
        String join = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        // 5、获取列表中每个blog的点赞和发布人
        for (Blog blog : blogs) {
            queryBlogUser(blog);
            // 3、判断是被点过赞
            isLikeBlog(blog);
        }
        // 6、封装ScrollResult并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);

    }

    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
